package baiqi.sishen.community.controller;

import baiqi.sishen.community.dto.FileDTO;
import baiqi.sishen.community.provider.QiNiuCloudProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * @author 兕神
 * @version 1.0
 * DateTime: 2023/5/3
 */
@Controller
@Slf4j
public class FileController {

    @Resource
    private QiNiuCloudProvider qiNiuCloudProvider;

    @PostMapping("/file/upload")
    @ResponseBody
    public FileDTO fileUpload(
            @RequestParam("myFile") List<MultipartFile> multipartFiles) {

        try {
            String[] data = new String[multipartFiles.size()];
            int count = 0;
            for (MultipartFile multipartFile : multipartFiles) {
                String url = qiNiuCloudProvider.upload(multipartFile.getInputStream(),
                        multipartFile.getContentType(), Objects.requireNonNull(multipartFile.getOriginalFilename()));
                data[count++] = url;
            }
            FileDTO fileDTO = new FileDTO();
            fileDTO.setErrno(0);
            fileDTO.setData(data);
            return fileDTO;
        } catch (Exception e) {
            log.error("upload error", e);
            FileDTO fileDTO = new FileDTO();
            fileDTO.setErrno(1);
            // fileDTO.setMessage("上传失败");
            return fileDTO;
        }
    }
}
